package com.project.frba.bi.extraction.database;

import com.project.frba.bi.descriptor.DatabaseDescriptor;
import com.project.frba.bi.descriptor.Descriptor;
import com.project.frba.bi.descriptor.Join;
import com.project.frba.bi.descriptor.Property;

public class QueryBuilder {
	
	private DatabaseDescriptor descriptor;
	private String query;
	
	public QueryBuilder() {

	}
	
	public QueryBuilder(DatabaseDescriptor descriptor){
		this.setDescriptor(descriptor);
	}
	
	public Descriptor getDescriptor() {	
		return descriptor;
	}

	public void setDescriptor(DatabaseDescriptor descriptor) {
		this.descriptor = descriptor;
	}
	
	public void buildQuery(){
		StringBuffer queryBuffer = new StringBuffer();
		queryBuffer.append(this.getSelect() + " ");
		queryBuffer.append(this.getFrom() + " ");
		queryBuffer.append(this.getJoins() + " ");
		queryBuffer.append(this.getWhere() + " ");
		queryBuffer.append(this.getGroupBy() + " ");
		queryBuffer.append(this.getHaving() + " ");
		queryBuffer.append(this.getOrder() + " ");
		this.query = queryBuffer.toString();
	}
	
	public String getQuery(){
		return this.query;
	}
	
	public String getSelect(){
		StringBuffer selectBuffer = new StringBuffer();
		selectBuffer.append("SELECT STRAIGHT_JOIN " + this.getDescriptor().getMetric() + " AS metric");
		for (Property property : this.getDescriptor().getProperties()) {
			if(property.getFunction() == null){
				selectBuffer.append(", " + property.getAbsolutePath());				
			} else {
				selectBuffer.append(", " + property.getFunction() + "(" + property.getAbsolutePath() + ")" );
			}
			selectBuffer.append(property.getAlias());
		}
		
		return selectBuffer.toString().trim();
	}
	
	public String getFrom(){
		StringBuffer fromBuffer = new StringBuffer();
		fromBuffer.append("FROM ");
		fromBuffer.append(this.getDescriptor().getFacttable());
		fromBuffer.append(" AS facttable");
		
		return fromBuffer.toString().trim();
	}
	
	public String getJoins(){
		StringBuffer bufferJoins = new StringBuffer();
		for(Join join: this.descriptor.getJoins()){
			bufferJoins.append(join.getJoin());
			bufferJoins.append(" ");
		}
		
		return bufferJoins.toString().trim();
	}
	
	public String getWhere(){
		return "";
	}
	
	public String getGroupBy(){
		StringBuffer groupByBuffer = new StringBuffer("GROUP BY ");
		for (Property property : this.getDescriptor().getProperties()) {
			groupByBuffer.append(property.getName() + ", ");
		}
		return groupByBuffer.substring(0, groupByBuffer.lastIndexOf(",")).trim();
	}
	
	public String getOrder(){
		return "";
	}
	
	public String getHaving(){
		return "";
	}

}
